package tech.aistar.corejava.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import tech.aistar.corejava.util.DateUtil;
import tech.aistar.corejava.xml.entity.Address;
import tech.aistar.corejava.xml.entity.Student;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/8/7 0007
 */
public class Dom4jParseStudent {
    public static void main(String[] args) {
        //1. 获取students.xml文件的字节输入流
        try {
            InputStream in = new FileInputStream("src/tech/aistar/corejava/xml/students.xml");

            //2. 创建SAXReader
            SAXReader saxReader = new SAXReader();

            //3. 获取Document
            Document document = saxReader.read(in);

            //4. 获取根标签
            Element root = document.getRootElement();

            //5. 获取根标签下面的所有的student标签

            List<Element> list = root.elements("student");

            //创建一个学生集合
            List<Student> students = new ArrayList<>();

            //6. 遍历list集合
            for (Element e : list) {//此处的e代表的是student
                //获取student的属性id的属性值
                //只要遇到一个student标签 - 创建student对象
                Student s = new Student();

                s.setId(Integer.valueOf(e.attributeValue("id")));


                //获取
                s.setName(e.elementTextTrim("name"));
                s.setNo(e.elementTextTrim("no"));

                s.setBirthday(DateUtil.parse(e.elementTextTrim("birthday"),"yyyy-MM-dd"));

                //先获取address标签对象
                Element addrElement = e.element("address");

                //判断存在
                if(null!=addrElement){
                    //创建address对象
                    Address address = new Address();

                    address.setProvince(addrElement.elementTextTrim("province"));
                    address.setCity(addrElement.elementTextTrim("city"));

                    //将address绑定student
                    s.setAddress(address);
                }

                students.add(s);
            }

            students.forEach(System.out::println);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
